package myJs.newPassword

import myJs.api.Api
import myJs.myPkg.yup.{TestContext, Yup}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Pojo.UserNameData

import scala.collection.mutable
import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.JSConverters._

/** Created by yz on 7/12/2022
  */
object Schema {

  case class ValidInfo(v: String, valid: Boolean)

  val cacheMap = mutable.SeqMap[String, ValidInfo]()

  def cacheTest(key: String)(f: String => Future[Boolean]) = (v: String) => {
    val beforeV = cacheMap.getOrElse(key, ValidInfo("", true))
    if (beforeV.v != v) {
      f(v).map { x =>
        cacheMap.put(key, ValidInfo(v, x))
        x
      }.toJSPromise
    } else {
      Future {
        beforeV.valid
      }.toJSPromise
    }
  }

  def nameValidateF(key: String) = cacheTest(key) { v: String =>
    val request = UserNameData(name = v)
    Api.validName(request).map { response =>
      !response.valid
    }
  }

  def captchaValidateF = (v: String, context: TestContext) => {
    val code = context.parent("code")
    code.toLowerCase == v.toLowerCase
  }

  val schema = Yup
    .`object`()
    .shape(
      js.Dictionary(
        "newPassword" -> Yup
          .string()
          .required("新密码不能为空！")
          .matches(
            regex =
              js.RegExp("^(?=\\w*\\d)(?=\\w*[A-Z])(?=\\w*[a-z])[\\w]{6,}$"),
            message = "密码只能由数字和字母组成，必须同时包含大小写，且不小于6位！"
          ),
        "newPasswordAgain" -> Yup
          .string()
          .required("确认密码不能为空！")
          .oneOf(enums = js.Array(Yup.ref("newPassword")), message = "两次密码不一样!")
      )
    )
}
